import { defineStore } from "pinia";
import { LoginType , login ,UserInfoType ,getUserInfo} from "@/api/login";

interface LoginStoreType{
    token:string,
    userinfo : UserInfoType
}

let user = defineStore(
    "User",
    {
        state:():LoginStoreType => {
            return {
                token :sessionStorage.getItem("token")||"",
                userinfo : {
                    name : sessionStorage.getItem("name")||"",
                    avatarUrl : sessionStorage.getItem("avatarUrl")||""
                }
            }
        },
        getters:{

        },
        actions:{
            //登录
            async doLogin(LoginForm:LoginType){
            let {code,data} = await login(LoginForm)
            if(code == 200){
                this.token = data
                sessionStorage.setItem("token",data)
                this.doGetUserInfo();
            }
        },
        async doGetUserInfo(){
            let {code,data} = await getUserInfo();
            if(code == 200){
                this.userinfo = data;
                sessionStorage.setItem("name",data.name);
                sessionStorage.setItem("avaraUrl",data.avatarUrl);
            }
         },
         doLogOut(){
            this.userinfo.name="";
            this.userinfo.avatarUrl="";
            this.token = "";
            sessionStorage.removeItem("name");
            sessionStorage.removeItem("avaraUrl");
            sessionStorage.removeItem("token");
         }
        }
    }
)
export default user;